import React, { useEffect, useState } from "react";
import { Form, Input, Button, Toast } from "antd-mobile";
import "./styles/Login.scss";
import { connect } from "react-redux";
import action from "../store/action";

import api from "../api";
import _ from "../utils/utils";

function Login(props) {
  const { setToken, getUserInfo, navigate, usp } = props;
  const [formRef] = Form.useForm();

  const [sendText, setSendText] = useState("发送验证码");

  const [submitLoading, setSubmitLoading] = useState(false);
  // 表单提交方法
  function onSubmit(values) {
    // 触发此事件说明已经触发了表单校验 并且校验成功   values是表单自动收集的信息
    const { phone, code } = values;
    setSubmitLoading(true);
    api
      .login(phone, code)
      .then((res) => {
        console.log(res);
        if (res.code === 0) {
          _.storage.set("tk", res.token);
          setToken(res.token);
          getUserInfo().then(() => {
            Toast.show({
              icon: "success",
              content: "登录成功",
            });
            const to = usp.get("to");
            console.log("to ", to);
            to ? navigate(to, { replace: true }) : navigate(-1);
          });
        } else {
          Toast.show({
            icon: "fail",
            content: "登录失败",
          });
          // 重置验证码
          formRef.resetFields(["code"]);
        }
      })
      .finally(() => {
        setSubmitLoading(false);
      });
  }
  // 手机号自定义校验规则
  function phoneRuleVerify(_, value) {
    const phoneReg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (value && !phoneReg.test(value)) {
      console.log(phoneReg.test(value));
      return Promise.reject(new Error("手机号格式错误"));
    }
    return Promise.resolve();
  }
  let timer,
    num = 31;

  const countdown = () => {
    num--;
    if (num === 0) {
      clearInterval(timer);
      timer = null;
      setSendText(`发送验证码`);
      return;
    }
    setSendText(`${num}秒后重发`);
  };
  async function sendCode() {
    if (timer) return;
    try {
      const phoneValidate = await formRef.validateFields(["phone"]);
      const { phone } = formRef.getFieldsValue(["phone"]);
      if (phoneValidate) {
        api.sendPhoneCode(phone);
        setSendText(`${num}秒重新发送`);
        countdown();
        if (!timer) timer = setInterval(countdown, 1000);
      }
    } catch (error) {}
  }
  useEffect(() => {
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, []);
  return (
    <div className="login-container">
      <Form
        form={formRef}
        layout="horizontal"
        mode="card"
        initialValues={{
          phone: "",
          code: "",
        }}
        requiredMarkStyle={false}
        onFinish={onSubmit}
        footer={
          <Button
            block
            color="primary"
            loading={submitLoading}
            size="large"
            type="submit"
          >
            {/* 需要加上type=submit 才能触发onFinish */}
            登录
          </Button>
        }
      >
        <Form.Item
          label="手机号"
          name="phone"
          rules={[
            {
              validator: phoneRuleVerify,
              validateTrigger: "onBlur",
            },
            {
              required: true,
              message: "手机号不能为空",
            },
          ]}
        >
          <Input maxLength={11} clearable type="text" />
        </Form.Item>
        <Form.Item
          rules={[
            {
              required: true,
              message: "验证码不能为空",
            },
          ]}
          label="短信验证码"
          name="code"
          extra={<a onClick={sendCode}>{sendText}</a>}
        >
          <Input />
        </Form.Item>
      </Form>
    </div>
  );
}

export default connect(null, {
  ...action.user,
})(Login);
